import React, {useState, useEffect, useRef} from "react";
import ApiService from "../../../utils/ApiService";
import {LoadingView} from "react-native-gzdsx-elements";
import {FlatList, Text, View} from "react-native";
import PostListItem from "./PostListItem";
import {useNavigation} from "@react-navigation/native";

const PostList = ({tabLabel, options = {}}) => {
    const navigation = useNavigation();

    const [dataList, setDataList] = useState([]);
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);

    const offset = useRef(0);
    const requesting = useRef(false);

    const fetchData = () => {
        ApiService.get('/posts', {
            params: {
                ...options,
                offset: offset.current,
                limit: 15,
                sort: 'time-desc'
            }
        }).then(response => {
            let {items} = response.result;
            if (loadingMore) {
                setDataList(dataList.concat(items));
            } else {
                setDataList(items);
            }
        }).finally(() => {
            requesting.current = false;
            setLoading(false);
            setRefreshing(false);
            setLoadingMore(false);
        })
    }

    useEffect(() => {
        fetchData();
        return () => {

        };
    }, []);

    useEffect(() => {
        if (refreshing) {
            offset.current = 0;
            fetchData();
        }
    }, [refreshing]);

    useEffect(() => {
        if (loadingMore) {
            offset.current += 15;
            fetchData();
        }
    }, [loadingMore]);

    const onRefresh = () => {
        if (requesting.current) {
            return false;
        }

        setRefreshing(true);
    }

    const onEndReached = () => {
        if (requesting.current) {
            return false;
        }

        if (dataList.length === total) {
            return false;
        }

        setLoadingMore(true);
    }

    if (loading) {
        return <LoadingView/>;
    }

    return <FlatList
        data={dataList}
        renderItem={({item, index}) => (
            <PostListItem item={item} onPress={() => {
                navigation.navigate('PostDetail', {id: item.id});
            }}/>
        )}
        keyExtractor={(item, index) => index.toString()}
        refreshing={refreshing}
        onRefresh={onRefresh}
        onEndReached={onEndReached}
        onEndReachedThreshold={0.2}
        ListEmptyComponent={() => {
            return (
                <View style={{padding: 50, alignItems: 'center', alignContent: 'center'}}>
                    <Text style={{fontSize: 16, color: '#666', textAlign: 'center'}}>此栏目下还没有内容</Text>
                </View>
            );
        }}
    />
}

export default PostList;
